package org.example.spring_frist.LibraryProject.server;

import org.example.spring_frist.LibraryProject.dao.booksDao;
import org.example.spring_frist.LibraryProject.model.bookInfo;
import org.example.spring_frist.LibraryProject.model.loginInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.example.spring_frist.LibraryProject.dao.booksAccountDao;

import java.util.List;

@Service
public class booksServer {

    @Autowired
    booksDao booksDao;
    @Autowired
    booksAccountDao booksAccountDao;
    //其实server可以直接使用mapper的dao和mapper存在一个就好

    //密码验证
    public Boolean verify(String username, String password) {
        List<loginInfo> list = booksAccountDao.getLoginInfo();

        for (loginInfo loginInfo : list) {
            if(loginInfo.getUsername().equals(username) && loginInfo.getPassword().equals(password)) {
                return true;
            }
        }
        return false;
    }

    //注册账户 储存密码
    public boolean register(String username, String password) {
        if(StringUtils.hasLength(username) || StringUtils.hasLength(password)) {
            return false;
        }
//        booksAccountDao.map.put(username, password);
        return true;
    }

    //删除书
    public boolean del(Integer id) {
        return booksDao.del(id) != 0;
    }

    //找到对应id得书
    private bookInfo findBookById(int id) throws NumberFormatException {
        return booksDao.getBookById(id);
    }

    //调整书的内容
    public Boolean adjust(int id, String name, String author,
                                 String count, String price, String publisher, String state) {
        bookInfo b = new bookInfo();
        b.setId(id);
        b.setName(name);
        b.setAuthor(author);
        b.setCount(Integer.parseInt(count));
        b.setPrice(Integer.parseInt(price));
        b.setPublisher(publisher);
        b.setState(Integer.parseInt(state));
        b.setStateCN(b.getState() == 1 ? "可借阅" : "不可借阅");

        return booksDao.adjust(b) != 0;
    }

    public Boolean addBook(String name, String author, String count, String price
            , String publisher, String state) {
        bookInfo b = new bookInfo();
        b.setName(name);
        b.setAuthor(author);
        b.setCount(Integer.parseInt(count));
        b.setPrice(Integer.parseInt(price));
        b.setPublisher(publisher);
        b.setState(Integer.parseInt(state));
        return booksDao.addBook(b) != 0;
    }

    //批量删除
    public Boolean dels(String[] bookId) {
        int ret = 0;
        for (String bookId1 : bookId) {
            ret+=booksDao.del(Integer.parseInt(bookId1));
        }
        return ret != 0;
    }

    public List<bookInfo> getBookList() {
        return booksDao.getBookList();
    }
}
